#!/usr/bin/env python
#-*- coding:utf-8 -*-

"""
Web2py Usage Reference

* Place the script in web2py/scripts directory
* make it executable:
    chmod +x mercurial_util.py
* For usage run the following from the web2py/applications directory:

    ../scripts/uc_tools/mercurial_util.py

* To update everything in the web2py/applications directory run this:

    ../scripts/uc_tools/mercurial_util.py --pullupdate --root=../applications

Original Script:

Updated Mercurial Batch Pull/Update Python Script
http://bluebill.wordpress.com/2010/04/05/updated-mercurial-batch-pullupdate-python-script/

This script is designed to work with mercurial. Its main purpose is to initiate
hg pull, push or update on a group of repositories stored in a root directory.

License:
The MIT License

Copyright (c) 2010 Troy Williams

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import sys
import os
import subprocess
import ConfigParser

__uuid__ = '2fa2a3dd-f271-4aef-a602-76ec29e32619'
__version__ = '0.1'
__author__ = 'Troy Williams'
__email__ = 'troy.williams@bluebill.net'
__copyright__ = 'Copyright (c) 2010, Troy Williams'
__date__ = '2010-04-05'
__license__ = 'MIT'
__maintainer__ = 'Troy Williams'
__status__ = 'Development'

def run_command(command, useshell=False):
    """
    Takes the list and attempts to run it in the command shell.
    """
    if not command:
        raise Exception, 'Valid command required - fill the list please!'

    p = subprocess.Popen(command, shell=useshell)
    retval = p.wait()
    return retval

def find_directories(root, dir_to_find):
    """
    Walks through the directory structure from the root and finds the
    directory names that match dir_to_find

    returns a list of paths matching the folder
    """
    foundDirs = []
    for root, dirs, files in os.walk(root):
        for d in dirs:
            if d.upper() == dir_to_find.upper():
                foundDirs.append(os.path.join(root, d))
    return foundDirs

def find_repositories(root):
    """
    Searches for mercurial repositories from along the root path.

    Returns a list of repository folders.
    """
    #Find all .hg folders. These indicate repositories
    dirs = find_directories(root, '.hg')

    #return the list of parent folder names
    return [os.path.dirname(item) for item in dirs]

def pull(dirs):
    """
    Issues the hg pull command on all valid repositories that were discovered on
    the root folder path
    """

    if not dirs:
        print "Mercurial repositories not found..."
        return

    for repo in dirs:
        print 'Pulling changes for repository: ', repo
        cmd = ['hg', 'pull', '-R', repo]
        run_command(cmd)

def push(dirs):
    """
    Issues the hg push command on all valid repositories
    """

    if not dirs:
        print "Mercurial repositories not found..."
        return
    for repo in dirs:
        print 'Pushing changes for repository: ', repo
        cmd = ['hg', 'push', '-R', repo]
        run_command(cmd)

def update(dirs):
    """
    Issues the hg update command on all valid repositories
    """

    if not dirs:
        print "Mercurial repositories not found..."
        return

    for repo in dirs:
        print 'Updating repository to tip: ', repo
        cmd = ['hg', 'update', '-R', repo]
        run_command(cmd)

def main():
    """
    Parse the command line and issue the appropriate mercurial command.
    """

    from optparse import OptionParser

    usage = "usage: %prog [options]"
    parser = OptionParser(usage=usage, version="%prog v" + __version__)
    parser.add_option("-p", "--pull", action="store_true",
                                      dest="pull",
                                      help="Pull remote changes to local \
                                      repository")
    parser.add_option("", "--pullupdate", action="store_true",
                                          dest="pullupdate",
                                          help="Pull remote changes to local \
                                                repository and update to \
                                                tip.")
    parser.add_option("-u", "--update", action="store_true",
                                         dest="update",
                                         help="Update local repositories to \
                                               tip.")
    parser.add_option("-s", "--push", action="store_true",
                                      dest="push",
                                      help="Push local changes to remote \
                                            repository.")
    parser.add_option("-r", "--root", dest="searchpath",
                                      help="Root folder containing all \
                                      repositories to search. Defaults to the \
                                      the same folder as the script.",
                                      default=sys.path[0],
                                      metavar="PATH")

    options, args = parser.parse_args(args=None, values=None)

    print "Searching ", options.searchpath
    dirs = find_repositories(options.searchpath)

    if options.pullupdate:
        pull(dirs)
        update(dirs)
    elif options.pull:
        pull(dirs)
    elif options.push:
        push(dirs)
    elif options.update:
        update(dirs)
    else:
        print parser.print_help()
        return -1

    return 0 # success

if __name__ == '__main__':
    status = main()
    sys.exit(status)

